package nl.hanze.designpatterns.mvc.view;

import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Panel;

import javax.swing.JButton;
import javax.swing.JLabel;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

import nl.hanze.designpatterns.domain.Answer;
import nl.hanze.designpatterns.domain.Question;
import nl.hanze.designpatterns.domain.ThesaurusItem;
import nl.hanze.designpatterns.mvc.controller.ThesaurusController;
import nl.hanze.designpatterns.mvc.model.ThesaurusModel;

public class ThesaurusView extends View<ThesaurusController, ThesaurusModel> {

	private JButton backButton;
	private JLabel title;
	private JLabel description;
	private Panel answerTable;
	
	public ThesaurusView(ThesaurusController controller, ThesaurusModel model) {
		super(controller, model);
		
		backButton = new JButton("Terug");
		backButton.addActionListener(controller);
		backButton.setActionCommand(controller.THESAURUS_BACK);
		title = new JLabel("DEFAULT TITLE");
		Font font = new Font("ARIAL", Font.BOLD, 24);
		title.setFont(font);
		description = new JLabel("DEFAULT DESCRIPTION");
		
		answerTable = new Panel(new GridLayout(0, 1, 0, 5));
		
		FormLayout layout = new FormLayout(
				"100dlu,200dlu",
				"p, 5dlu, p, 5dlu, p, 5dlu, p");
		
		PanelBuilder builder = new PanelBuilder(layout);
		CellConstraints cc = new CellConstraints();
		
		builder.add(backButton, cc.xy(1, 1));
		builder.add(title, cc.xyw(1, 3, 2));
		builder.add(description, cc.xyw(1, 5, 2));
		builder.add(answerTable, cc.xyw(1, 7, 2));
		
		this.add(builder.getPanel());
		
		load();
	}
	
	private void load(){
		ThesaurusItem item = getModel().getCurrent();
		if(item != null){
			if(item instanceof Question){
				title.setText(((Question) item).getQuestion());
				for(ThesaurusItem i : ((Question) item).getItems()){
					JButton button = new JButton(i.getAnswer());
					button.addActionListener(getController());
					button.putClientProperty("item", i);
					button.setActionCommand(ThesaurusController.THESAURUS_SELECT);
					answerTable.add(button);
				}
			}else if(item instanceof Answer){
				title.setText(item.getAnswer());
			}
			description.setText(item.getDescription());
			backButton.setEnabled(!getModel().isRootItem());
			revalidate();
		}
	}

	@Override
	public void notifyChange() {
		answerTable.removeAll();
		load();
	}

}
